package security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import security.domain.Permission;
import security.domain.User;
import security.mapper.UserMapper;
import security.service.UserService;
import security.utils.JwtUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService, UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private AuthenticationManager manager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User u = userMapper.selectOne(queryWrapper);
        if (u == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //获取用户权限
        List<Permission> permission = userMapper.getAllPermission(u.getId());
        //返回对象
        return new LoginUser(u,permission);
    }

    @Override
    public String login(User user) throws JsonProcessingException {
        //进行认证
        Authentication authenticate = manager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        //认证失败 抛出异常
        if (authenticate == null) {
            throw new RuntimeException("认证失败");
        }
        //获取当前认证通过的对象
        LoginUser principal = (LoginUser) authenticate.getPrincipal();
        //获取用户，根据id生成jwt，将用户实体存放在redis
        Integer id = principal.getUser().getId();
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        String token = JwtUtil.createJWT("qwe!@#123", 1000*60*60*24, map);
        String user_json = objectMapper.writeValueAsString(principal);
        redisTemplate.opsForValue().set("login:" + id, user_json);
        return token;
    }

    @Override
    public void logout() {
        //从Holder获取用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //清除redis中的信息
        redisTemplate.delete("login:"+loginUser.getUser().getId());
        //清除SecurityContextHolder中的信息
        SecurityContextHolder.clearContext();
    }
}
